package com.hspedu.tankgame5;

import java.awt.*;
import java.io.*;
import java.util.Vector;

/**
 * @author LiuJinTao
 * @className Recorder
 * @date 2024/10/23 9:22
 * @description TODO
 */
public class Recorder {

    // 定义变量，记录我方击毁敌人坦克数
    private static int allEnemyTankNum = 0;
    // 定义IO对象，准备写数据到文件中
    private static BufferedWriter bw = null;
    private static BufferedReader br = null;
    private static String recordFile = "src\\myRecord.txt";
    // 敌人坦克的vector
    private static Vector<Enemy> enemys = null;
    // 定义一个 Node 的 Vector 用于保存敌人的信息 Node
    private static Vector<Node> nodes = new Vector<Node>();

    // 增加一个方法，用于读取 recordFile，恢复相关的文件
    public static Vector<Node> getNodes() {
        try {
            br = new BufferedReader(new FileReader(recordFile));
            allEnemyTankNum = Integer.parseInt(br.readLine());
            // 循环读取文件，生成 nodes 集合
            String line = "";
            while ((line = br.readLine()) != null) {
                String[] s = line.split(" ");
                nodes.add(new Node(Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2])));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return nodes;
    }

    public static void setEnemis(Vector<Enemy> enemis) {
        Recorder.enemys = enemis;
    }

    // 返回记录文件的路径
    public static String getRecordFile() {
        return recordFile;
    }

    //增加一个方法，当我们退出时，我们将 allEnemyTankNum 保存到 recordFile
    // 升级，保存敌人坦克坐标和方向
    public static void keepRecord() {
        try {
            bw = new BufferedWriter(new FileWriter(recordFile));
            bw.write(allEnemyTankNum +"\r\n");
            // 遍历敌人坦克的 vector ，根据情况保存
            for (int i = 0; i < enemys.size(); i++) {
                // 取出敌人坦克
                Enemy enemy = enemys.get(i);
                if (enemy.isLive) {
                    bw.write(enemy.getX() + " " + enemy.getY() + " " + enemy.getDirect() + "\r\n");

                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static int getAllEnemyTankNum() {
        return allEnemyTankNum;
    }

    public static void setAllEnemyTankNum(int allEnemyTankNum) {
        Recorder.allEnemyTankNum = allEnemyTankNum;
    }

    // 当我方坦克击毁一个敌方坦克，就应当 allEnemyTankNum++
    public static void addAllEnemyTankNum() {
        Recorder.allEnemyTankNum++;
    }
}

